package com.monolithiot.sso.service.impl;

import com.monolithiot.sso.common.entity.User;
import com.monolithiot.sso.common.entity.UserGroup;
import com.monolithiot.sso.common.entity.UserGroupRole;
import com.monolithiot.sso.common.exception.AlreadyExistedException;
import com.monolithiot.sso.common.exception.ServiceUnforeseenException;
import com.monolithiot.sso.dao.BaseMapper;
import com.monolithiot.sso.dao.mapper.UserGroupRoleMapper;
import com.monolithiot.sso.service.UserGroupRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 2018/12/30 Create by 郭文梁
 * UserGroupRoleServiceImpl
 * 用户组角色业务行为实现
 *
 * @author 郭文梁
 * @date 2018/12/30
 */
@Service
public class UserGroupRoleServiceImpl extends BaseServiceImpl<UserGroupRole> implements UserGroupRoleService {
    private final UserGroupRoleMapper userGroupRoleMapper;

    @Autowired
    public UserGroupRoleServiceImpl(UserGroupRoleMapper userGroupRoleMapper) {
        this.userGroupRoleMapper = userGroupRoleMapper;
    }

    @Override
    BaseMapper<UserGroupRole> getMapper() {
        return userGroupRoleMapper;
    }

    @Override
    public UserGroupRole join(User user, UserGroup userGroup) throws AlreadyExistedException {
        UserGroupRole role = findByUserAndGroup(user, userGroup);
        if (role != null) {
            throw new AlreadyExistedException();
        }
        role = new UserGroupRole();
        role.setUserId(user.getId());
        role.setUser(user);
        role.setUserGroupId(userGroup.getId());
        role.setUserGroup(userGroup);
        role.setState(UserGroupRole.STATE_CREATE);
        return save(role);
    }

    @Override
    public UserGroupRole findByUserAndGroup(User user, UserGroup userGroup) {
        UserGroupRole query = new UserGroupRole();
        query.setUserGroupId(userGroup.getId());
        query.setUserId(user.getId());
        return getMapper().selectOne(query);
    }

    @Override
    public List<UserGroupRole> findByUserWithGroup(User user) {
        return userGroupRoleMapper.findByUserWithGroup(user);
    }

    @Override
    public List<UserGroupRole> findNotPassRulesByCreator(User user) {
        return userGroupRoleMapper.findNotPassByCreatorWithGroupAndUser(user);
    }

    @Override
    public void agreeApply(UserGroupRole role) {
        role.setState(UserGroupRole.STATE_PASS);
        UserGroupRole res = update(role);
        if (res == null) {
            throw new ServiceUnforeseenException("Could not update UserGroupRole " + role);
        }
    }
}
